package com.oa.android.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.FujAdapter;
import com.oa.android.entry.Fjian;
import com.oa.android.entry.Work;
import com.oa.android.utils.FileMange;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;


/**
 *
 * 个人工作详情
 * @author -zouqh
 * 
 */
public class DetailsWorkActivity extends Activity implements OnClickListener {

	private ImageView close;
	private TextView title,emilTitle,tiem,form,lastTime;
	private MyGridView gridView;
	private WebView webView;
	private Work work;
	private String[] fuj;
	private FujAdapter adapter;
	private ScrollView myScrollView;
	private ProgressDialog progressDialog;
	private Dialog Jdialog;

	private FileMange fileMange;

	private   String filePath = Environment.getExternalStorageDirectory().getPath() + File.separator+"ZHOA"+ File.separator;
	List<Fjian> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.details_work_activity);
		close = (ImageView) findViewById(R.id.close);
		title = (TextView) findViewById(R.id.title_text);
		emilTitle= (TextView) findViewById(R.id.emilTitle);
		tiem= (TextView) findViewById(R.id.time);
		form= (TextView) findViewById(R.id.form);
		lastTime= (TextView) findViewById(R.id.lastTime);
		webView= (WebView) findViewById(R.id.emilContent);
		gridView=(MyGridView)findViewById(R.id.gridview);
		myScrollView = (ScrollView)findViewById(R.id.myScrollView);
		myScrollView.smoothScrollTo(0, 20);
		title.setText("工作详情");
//		clearCookies(this);
		work= (Work) getIntent().getSerializableExtra("work");
		close.setOnClickListener(this);
//		webView.setWebChromeClient(new MyWebChromeClient(HuiNiuActivity.this));//
//		webView.setWebViewClient(new MyWebViewClient(noNet, HuiNiuActivity.this));//
		progressDialog = ProgressDialog.show(this, null, "加载中...", true, false);
		WebSettings webSettings = webView.getSettings();
		webSettings.setSupportZoom(true); // 设置是否支持变焦
		webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕大小
		webSettings.setUseWideViewPort(true);// 将图片调整到是个webview的大小
		webSettings.setDefaultTextEncodingName("utf-8");// 设置编码格式
		webSettings.setLoadsImagesAutomatically(true);// 支持自动加载图片
		webSettings.setJavaScriptEnabled(true);//
		webSettings.setSupportMultipleWindows(true);// 支持多窗口
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);// 支持js打开新窗口
		webSettings.setDomStorageEnabled(true);
		String appCacheDir = this.getApplicationContext()
				.getDir("cache", Context.MODE_PRIVATE).getPath();
		webSettings.setAppCachePath(appCacheDir);
		webSettings.setAllowFileAccess(true);
		webSettings.setAppCacheEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		fileMange=new FileMange(this);


		webView.addJavascriptInterface(new JsInterface(this), "AppView");

		getFj();

		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {

				super.onPageFinished(view, url);
				JSONObject object=new JSONObject();
				try {
					object.put("ID",work.getID());
					object.put("EMPID",work.getEMPID());
					object.put("EMPNAME",work.getEMPNAME());
					object.put("CUREMPID",UConstants.EmpId);
					object.put("CUREMPNAME",UConstants.EmpName);
					object.put("DEPID",UConstants.DepId);
					object.put("DEPNAME",UConstants.EmpName);
					object.put("FS","1");
					object.put("SPID",work.getSPID());
					object.put("WKFID",work.getWKFID());
					object.put("NEMPIDS",work.getNEMPIDS());
					object.put("WKZT",work.getWKZT());
					object.put("FORMURL",work.getFORMURL()+"l");

				} catch (JSONException e) {
					e.printStackTrace();
				}
				Log.e("onPageFinished---object.toString()",object.toString());
				webView.loadUrl("javascript: GetContent('"+object.toString()+"')");
			}
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				progressDialog.dismiss();
			}




		});

		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				Log.i("newProgress---",""+newProgress);
				// TODO Auto-generated method stub
				if (newProgress == 100) {
					// 网页加载完成
					progressDialog.dismiss();
				} else {
					// 加载中

				}

			}


		});

//		work.setFORMCONTENT("<P>申请人：<INPUT id=Text2 style=\\\"BORDER-TOP: 0px; BORDER-RIGHT: 0px; BORDER-BOTTOM: #000000 1px solid; BORDER-LEFT: 0px\\\" readOnly value=宏控件-用户姓名 name=4991></P><P>申请部门：<INPUT id=Text2 style=\\\"BORDER-TOP: 0px; BORDER-RIGHT: 0px; BORDER-BOTTOM: #000000 1px solid; BORDER-LEFT: 0px\\\" readOnly value=宏控件-用户部门 name=4825></P><P>事由：<TEXTAREA id=TextArea1 style=\\\"SCROLLBAR-HIGHLIGHT-COLOR: #d8d8d8; BORDER-TOP: 0px; BORDER-RIGHT: 0px; SCROLLBAR-TRACK-COLOR: #d8d8d8; SCROLLBAR-FACE-COLOR: #aaaaaa; BORDER-BOTTOM: #000000 1px solid; SCROLLBAR-3DLIGHT-COLOR: #d8d8d8; SCROLLBAR-ARROW-COLOR: #d8d8d8; BORDER-LEFT: 0px; SCROLLBAR-SHADOW-COLOR: #d8d8d8; SCROLLBAR-DARKSHADOW-COLOR: #d8d8d8\\\" name=6635></TEXTAREA></P><P>申请时间：<INPUT id=Text2 style=\\\"BORDER-TOP: 0px; BORDER-RIGHT: 0px; BORDER-BOTTOM: #000000 1px solid; BORDER-LEFT: 0px\\\" readOnly value=宏控件-当前时间(日期) name=15655></P><P>&nbsp;</P>");
		if (work!=null){
			emilTitle.setText(work.getWORKNAME());
			tiem.setText("创建时间："+work.getOPTIME());
			form.setText("发起人："+work.getEMPNAME());
			lastTime.setText("最后一次激活时间:"+work.getLATETIME());
			String url=UConstants.DZ+"Samples/"+work.getFORMURL()+"l";

			webView.loadUrl(url);

//			if (Util.NoNull(work.getFUJIANLIST())){
//				if (work.getFUJIANLIST().contains("|")){
//					fuj=work.getFUJIANLIST().split("\\|");
//				}else{
//					fuj=new String[]{work.getFUJIANLIST()};
//				}
//				adapter=new FujAdapter(this,fuj);
//				gridView.setAdapter(adapter);
//				fileMange=new FileMange(this);
//
//			}
		}

		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.i("position===",""+position);
				if (!new File(filePath+list.get(position).getOLDNAME()).exists()){

					if (Util.NoNull(list.get(position).getNOWNAME())){

						String[] bs= list.get(position).getNOWNAME().split("/");
						StringBuffer brf = new StringBuffer();
						for (int i = 0; i < bs.length; i++) {
							if(i==bs.length-1){

								try {
									brf.append(URLEncoder.encode(bs[i],"UTF-8").replaceAll("\\+", "%20"));
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}else {
								brf.append(bs[i]).append("/");
							}

						}

						pointDialog("您需要下载此文件吗？",1,brf.toString(),list.get(position).getOLDNAME());
					}else{
						Toast.makeText(DetailsWorkActivity.this,"下载地址有误",Toast.LENGTH_SHORT).show();
					}

//
				}else{
					pointDialog("您需要打开此文件吗？",0,list.get(position).getOLDNAME(),list.get(position).getOLDNAME());
//					openFile(new File(filePath+fuj[position]));
				}

			}
		});

	}




	private class JsInterface {
		private Context mContext;

		public JsInterface(Context context) {
			this.mContext = context;
		}

		// 在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
		@JavascriptInterface
		public void showInfoFromJs(String json) {

		}



		@JavascriptInterface
		public String isNetwork() {

			return "00";
		}
		@JavascriptInterface
		public void cellPhone(String phone) {

			if (null!=phone&&phone.length()>0){
				Uri telUri = Uri.parse("tel:" + phone);
				Intent intent = new Intent(Intent.ACTION_DIAL, telUri);
				startActivity(intent);
			}else{
				Toast.makeText(DetailsWorkActivity.this,"电话不能为空",Toast.LENGTH_SHORT).show();
			}
		}


	}

	WebChromeClient wvcc = new WebChromeClient() {
		@Override
		public void onReceivedTitle(WebView view, String title) {
			super.onReceivedTitle(view, title);
			Log.d("ANDROID_LAB", "TITLE=" + title);

		}



	};

	class Handler {
		public void show(String data) {
			Toast.makeText(DetailsWorkActivity.this,"执行了handler.show方法",10).show();
			new AlertDialog.Builder(DetailsWorkActivity.this).setMessage(data).create().show();
		}
	}

	/**
	 * 提示
	 */
	private void pointDialog(String str, final int p, final String pat, final String odfile) {
		LayoutInflater inflaterDl = LayoutInflater.from(this);
		View layout = inflaterDl.inflate(R.layout.exti_dialog,
				null);
		// 对话框
		Jdialog = new Dialog(this);
		Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		Jdialog.show();

		Jdialog.setContentView(layout);
		TextView sure = (TextView) layout.findViewById(R.id.sureExti);
		TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
		TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
		dialogTitle.setText(str);
		sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
				Jdialog.cancel();
				if(p==1){
					downloadFile(UConstants.URL_DOWN+pat,filePath+odfile);
				}else{
					fileMange.openFile(new File(filePath+odfile));
				}




			}
		});
		cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Jdialog.dismiss();
			}
		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		Intent intent ;
		switch (v.getId()) {
		case R.id.close:
//			Log.i("测试。。。。。",work.getFORMCONTENT());
//			Log.i("测试AAAAAAAAAA。。。。。",content.getUrl()+"");

			finish();
			break;

		default:
			break;
		}
	}


	private void downloadFile(final String url, String path) {
		Log.i("url---",url);
		progressDialog = new ProgressDialog(this);
		RequestParams requestParams = new RequestParams(url);
		requestParams.setSaveFilePath(path);
		x.http().get(requestParams, new Callback.ProgressCallback<File>() {
			@Override
			public void onWaiting() {
			}

			@Override
			public void onStarted() {
			}

			@Override
			public void onLoading(long total, long current, boolean isDownloading) {
				progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				progressDialog.setMessage("下载中...");
				progressDialog.show();
				progressDialog.setMax((int) total);
				progressDialog.setProgress((int) current);
			}

			@Override
			public void onSuccess(File result) {
				Toast.makeText(DetailsWorkActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
				progressDialog.dismiss();
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				ex.printStackTrace();
				Toast.makeText(DetailsWorkActivity.this, "下载失败，文件不存在或网络问题！", Toast.LENGTH_SHORT).show();
				progressDialog.dismiss();
			}

			@Override
			public void onCancelled(CancelledException cex) {
			}

			@Override
			public void onFinished() {
			}
		});
	}


	//获取附件
	public void getFj() {
		Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);
//		progressDialog = ProgressDialog.show(this, null, "加载中...", true, false);
		RequestParams params = new RequestParams(UConstants.GET_FJLIST);
		params.addBodyParameter("LKind", "OA");
		params.addBodyParameter("TNAME", "ERPGZGL");
		params.addBodyParameter("XH", work.getID());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Util.printLog("getDownRoute------------onSuccess-----", result);
				if (result.length() > 0) {
					try {
						JSONObject object = new JSONObject(result);
						boolean success = object.getBoolean("success");
//						String msg = object.getString("msg");
						if (success) {
							Gson gson = new Gson();
							Type lt = new TypeToken<List<Fjian>>() {
							}.getType();
							list = gson.fromJson(object.getString("rows").toString(), lt);
							if (list != null && list.size() > 0) {
								adapter=new FujAdapter(DetailsWorkActivity.this,list);
								gridView.setAdapter(adapter);
							}


						} else {
							Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();

						}
//
					} catch (JSONException e) {

						Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
				}
//				progressDialog.dismiss();

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

				Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
//				progressDialog.dismiss();
			}

			@Override
			public void onCancelled(CancelledException cex) {

				Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
				Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
//				progressDialog.dismiss();
			}

			@Override
			public void onFinished() {

			}
		});
	}


}
